<head>
<style>
.tool_label {
  display: inline-block;
}
</style>
</head>

<div id="tool_label" class="tool_label">
	<span>
	&nbsp;&nbsp;<%:Current Config File%>:&nbsp;
	<select id="cfg_name">
	</select>&nbsp;&nbsp;
	<input type="button" class="btn cbi-button cbi-button-apply" value="<%:Switch Config%>" onclick="return switch_config(this)" />
	&nbsp;
	</span>
</div>

<script type="text/javascript">//<![CDATA[
	var config_name = document.getElementById('cfg_name');
	var tool_label = document.getElementById('tool_label');
	var header1 = document.getElementsByClassName("tabmenu-item-log ")[0];
	var header2 = document.getElementsByClassName("tabmenu-item-client ")[0];
	var header3 = document.getElementsByClassName("tabmenu-item-config ")[0];
	
	if (header1 && header2.className != "tabmenu-item-client active" && header3.className != "tabmenu-item-config active") {
		insertAfter(tool_label,header1);
	}
	else {
		tool_label.style.display = "none";
	}
	
	if (tool_label.style.display != "none") {
		XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "config_name")%>', null, function(x, status) {
			if (x && x.status == 200 && status.config_name != "") {
				for(var i in status.config_name){
      	  config_name.options.add(new Option(status.config_name[i].name,status.config_name[i].name));
    		}
    		if (status.config_path != "") {
    			config_name.value = status.config_path;
    		}
    		else
    		{
    			config_name.options.add(new Option("<%:Not Select%>",""));
    			config_name.value = "";
    		}
			}
			else if (x && x.status == 200 && status.config_path != "") {
				config_name.options.add(new Option(status.config_path,status.config_path));
				config_name.value = status.config_path;
			}
			else {
				tool_label.style.display = "none";
			}
		});
	}
	
	function insertAfter( newElement, targetElement ){
    var parent = targetElement.parentNode;
    if( parent.lastChild == targetElement ){
        parent.appendChild( newElement, targetElement ); 
    }else{ 
        parent.insertBefore( newElement, targetElement.nextSibling );
    };
	};
	
	function switch_config(btn)
	{
		if (config_name.value && config_name.value != "") {
			btn.disabled = true;
			XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "switch_config")%>', {config_name: config_name.value}, function(x, status) {
				if (x && x.status == 200) {
    			btn.disabled = false;
    			alert(config_name.value + ' <%:switching succeeded!%>')
				}
				else {
					alert(config_name.value + ' <%:switching failed!%>')
				}
			});
			return false;
		}
	}
//]]></script>